//== 登录 Class
let login = function () {
    /**
     * 默认登录失败累计多少次后需要输入验证码后才可以登录
     * @type {number}
     */
    let loginAttemptsVerificationCode = 5;
    /**
     * 登录尝试次数
     * @type {number}
     */
    let loginAttempts = 0;
    //== 私有函数
    /**
     * 显示提示信息
     *
     * @param form 表单
     * @param type 提示类型
     * @param msg 文字
     */
    let showMsg = function (form, type, msg) {
        let alert = $('<div class="alert alert-' + type + '" role="alert">\
			<button type="button" class="close" data-dismiss="alert" aria-label="Close"></button>\
			<span></span>\
		</div>');

        form.find('.alert').remove();
        alert.prependTo(form);
        EApp.animateCSS(alert[0], 'fadeIn');
        alert.find('span').html(msg);
    };
    /**
     * 表单验证
     * @param $form {object} 表单对象
     * @param data {object} 表单内容
     * @return {boolean} true/false
     */
    let validate = function ($form, data) {
        if (EUtil.isBlank(data.username)) {
            showMsg($form, 'danger', '请输入用户名');
            return false;
        }
        if (EUtil.isBlank(data.password)) {
            showMsg($form, 'danger', '请输入密码');
            return false;
        }
        if (loginAttempts >= loginAttemptsVerificationCode && EUtil.isBlank(data.code)) {
            showMsg($form, 'danger', '请输入验证码');
            return false;
        }
        return true;
    };
    /**
     * 登录
     */
    let login = function () {
        let $form = $('form');
        let data = {
            username: $form.find('[name="username"]').val(),
            password: $form.find('[name="password"]').val(),
            code: $form.find('[name="code"]').val(),
            rememberMe: $form.find('[name="rememberMe"]').prop('checked')
        };
        if (validate($form, data)) {
            data.password = $.md5(data.password);
            let $btnLogin = $('#btn-login');
            EUtil.setButtonWait($btnLogin);
            EUtil.ajax({
                url: basePath + '/login',
                type: 'post',
                data: data,
                needAlert: false,
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    let res = XMLHttpRequest.responseJSON;
                    loginAttempts++;
                    EUtil.offButtonWait($btnLogin);
                    if (loginAttempts >= loginAttemptsVerificationCode || '203013' === res.code) {
                        // 登录失败次数达到设定值,需要输入验证码才能登录
                        $('.verification-group').removeClass('e-hide');
                    }
                    if ('303014' === res.code || '300401' === res.code) {
                        // 验证码过期或用户名或密码错误时，更换验证码，防止暴力破解；只是验证码失败勿更换，会降低用户体验
                        changeVerificationCode();
                    }
                    showMsg($form, 'danger', res.message);
                },
                success: function (res) {
                    showMsg($form, 'success', '登录成功');
                    if (EUtil.isNotBlank(basePath)) {
                        window.location.href = basePath;
                    } else {
                        window.location.href = '/';
                    }
                }
            });
        }
    };
    /**
     * 检查会话
     * 如会话过期，并且当前页面是顶级页面直接打开；否则提示会话过期原因并将顶级页面转到登录
     */
    let checkSession = function () {
        let sessionInvalid = $('#sessionInvalid').val();
        if ('1' === sessionInvalid && !EUtil.isTopPage()) {
            // 表示会话是被异地登录或踢出导致失效，当前页面不是顶级页面，需要弹框提示会话失效信息
            EUtil.alert({
                title: '会话过期',
                text: $('.alert-danger > .alert-text').html(),
                type: 'warning',
                confirmButtonText: '确定'
            }, function () {
                // 将顶级页面转到登录
                window.top.location.href = window.location.href;
            });
        } else {
            // 正常访问登录页面
            $('.e-login').removeClass('e-hide');
        }
    };
    /**
     * 更换验证码
     */
    let changeVerificationCode = function () {
        $('.verification-code img').attr('src', basePath + '/get/verification/code?' + new Date().getTime());
    };

    //== 公开函数
    return {
        init: function () {
            // 检查会话是否过期，防止用户操作中会话失效，登录页面在页面内部打开
            checkSession();
            try{
                // 系统参数中配置
                loginAttemptsVerificationCode = Number($('#loginAttemptsVerificationCode').val());
            } catch (e) {
            }
            $('#btn-login').click(function () {
                login();
            });
            $('.verification-code img').click(function () {
                changeVerificationCode();
            });
        }
    };
}();

//== Class 初始化
$(document).ready(function () {
    login.init();
});